package com.outdoor.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.util.List;

/**
 * Jackson配置类
 */
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        
        // 注册自定义反序列化器
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new ArrayToStringDeserializer());
        objectMapper.registerModule(module);
        
        return objectMapper;
    }

    /**
     * 数组转字符串反序列化器
     * 解决JSON数组转为Java字符串的问题
     */
    public static class ArrayToStringDeserializer extends JsonDeserializer<String> {
        @Override
        public String deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
            // 如果是数组，则转换为逗号分隔的字符串
            if (parser.isExpectedStartArrayToken()) {
                List<String> list = parser.readValueAs(List.class);
                return String.join(",", list);
            }
            
            // 如果是字符串，则直接返回
            return parser.getValueAsString();
        }
    }
} 